import axios from 'axios';
import { authService } from './authService';
import { Message } from '@/types';

interface GetMessagesResponse {
  success: boolean;
  data: Message[];
}

class MessageService {
  private getAuthHeaders() {
    const token = authService.getStoredToken();
    return {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    };
  }

  async getMessages(page = 1, limit = 50): Promise<Message[]> {
    console.log('📡 [DEBUG] messageService.getMessages() 开始');
    console.log('📡 [DEBUG] 请求参数:', { page, limit });
    
    try {
      const headers = this.getAuthHeaders();
      console.log('📡 [DEBUG] 请求头:', headers);
      
      const response = await axios.get<GetMessagesResponse>(
        '/api/v1/messages',
        {
          params: { page, limit },
          headers,
        }
      );

      console.log('📡 [DEBUG] API响应状态:', response.status);
      console.log('📡 [DEBUG] API响应数据:', response.data);

      if (response.data.success) {
        console.log('✅ [DEBUG] 消息获取成功，数量:', response.data.data.length);
        return response.data.data;
      }
      throw new Error('获取消息失败');
    } catch (error) {
      console.error('❌ [DEBUG] messageService.getMessages() 失败:', error);
      if (axios.isAxiosError(error)) {
        console.error('❌ [DEBUG] 错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        });
      }
      throw error;
    }
  }

  async sendMessage(content: string, type: 'text' | 'image' = 'text'): Promise<Message> {
    console.log('📤 [DEBUG] messageService.sendMessage() 开始');
    console.log('📤 [DEBUG] 发送参数:', { content, type });
    
    try {
      const headers = this.getAuthHeaders();
      console.log('📤 [DEBUG] 请求头:', headers);
      
      const response = await axios.post<{ success: boolean; data: Message }>(
        '/api/v1/messages',
        { content, type },
        {
          headers,
        }
      );

      console.log('📤 [DEBUG] API响应状态:', response.status);
      console.log('📤 [DEBUG] API响应数据:', response.data);

      if (response.data.success) {
        console.log('✅ [DEBUG] 消息发送成功:', response.data.data);
        return response.data.data;
      }
      throw new Error('发送消息失败');
    } catch (error) {
      console.error('发送消息失败:', error);
      throw error;
    }
  }
}

export const messageService = new MessageService();
export default messageService;